/*
 * @Date: 2023-01-25 02:02:22
 * @LastEditors: 恶名扬 2080156129@qq.com
 * @LastEditTime: 2023-01-25 03:49:10
 * @FilePath: \web\src\utils\request.js
 */
import store from '@/store'
import router, { resetRouter } from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'

// 创建添加自定义配置的axios
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

const form = (data) => {
  for (const item in data) {
    if (typeof data[item] === 'string') data[item].replace(/ /g, '')
    if (typeof data[item] === 'boolean') continue
    else if (typeof data[item] === 'number' && (item === 'permission' || item === 'state')) continue
    else if (!data[item]) delete data[item]
  }
}

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = store.getters.token
    if (token && config.url.indexOf('/user/') !== 0) {
      config.headers.Authorization = `Bearer ${token}`
    }
    config.data && form(config.data)
    config.params && form(config.params)

    return config
  },
  (err) => Promise.reject(err)
)

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    const { message, code } = response.data
    code === 10000
      ? message !== '请求成功'
        ? Message.success(message)
        : console.log()
      : Message.error(message)
    return response.data
  },
  async (err) => {
    Message.error(err?.response?.data?.message || err.message)
    if (err?.response?.data?.code === 10006) {
      store.commit('user/REMOVE_TOKEN')
      store.commit('user/RESET_STATE')
      resetRouter() // 重置路由
      router.push('/login')
    } else return Promise.reject(err)
  }
)

export default service
